using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;

namespace CECompactStartMenu
{
    /// <summary>
    /// There are three ways to run this app:
    /// (1) No commandline parameters : Use shortcuts in \Windows\StartMenu
    /// (2) Parameters = \\Windows or similar : search for .exe in \Windows
    /// (3) Parameters = temp or similar : Search \temp folders one deep in \temp for .exes (As placed there by SDK developement
    /// (4) .. Actually any folder off root with subfolders can be used as for (3)
    /// </summary>
    public partial class CECompactStartMenu : Form
    {
        public const int formTextAreaHeight = 32;
        public string rootDir { get; set; }
        public string fileType { get; set; }
        public bool IsStartMenu {get; set;}
        public Point location { get; set; }
        public CECompactStartMenu()
        {
            InitializeComponent();
            rootDir = "\\temp";
            location = this.location;
            IsStartMenu = false;
        }

        protected  void OnMove(object sender, EventArgs ea)
        {
            Invalidate();
        }

        List<System.IO.FileInfo> fileList;

        private void Form1_Load(object sender, EventArgs e)
        {
            //Search for shortcuts or .exe
            string[] tempdirs;
            string filter = "*.*";//Default menu item type. Set to .lnk for shortcuts
            bool searchingOneDeep = false;
            bool abort = false;
            
            if (Program.Args.Length != 0)
            {
                if (Program.Args[0] != "")
                {
                    rootDir = Program.Args[0];
                    if (rootDir.Substring(0, 1) != "\\")
                    {
                        //Just do toplevel directory of root. eg.windows will just search \windows
                        tempdirs = new string[] { "\\" + rootDir };
                    }
                    else
                    {
                        if (!Directory.Exists(rootDir))
                        {
                            //Check that the folder exists
                            MessageBox.Show("Menu folder " + rootDir + " doesn't exist. Exiting Menu app.", "CECompactStartMenu",
                                MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                            abort = true;
                        }
 
                        //Get folder directories one deep. eg \temp will search all folders immediately under temp
                        tempdirs = System.IO.Directory.GetDirectories(rootDir);
                        searchingOneDeep = true;
                        if (tempdirs.Length == 0)
                        {
                            //Check that there are folders one deeps
                            MessageBox.Show("No folders to search for menu items in: " + rootDir + ". Exiting Menu app.", "CECompactStartMenu",
                                MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                            abort = true;
                        }
                    }
                }
                else
                {
                    //Shouldn't get to this.
                    rootDir = "\\Windows\\Start Menu";
                    tempdirs = new string[] {rootDir };
                    IsStartMenu = true;
                }

            }
            else
            {
                //If no parameter then use following dir shortcuts
                rootDir = "\\Windows\\Start Menu";
                tempdirs = new string[] { rootDir };
                IsStartMenu = true;
                filter = "*.lnk";

            }


            this.Text = "Apps in " + rootDir;

            fileList = new List<FileInfo>();
            listBox1.Items.Clear();
            listBox1.Items.Add("Cancel");

            if (!abort)
            {
                if (!searchingOneDeep)
                {
                    //If only doing one directory then do some checks
                    if (!Directory.Exists(rootDir))
                    {
                        //Check that the folder exists
                        MessageBox.Show("Menu folder " + rootDir + " doesn't exist. Exiting Menu app.", "CECompactStartMenu",
                            MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                        abort = true;
                    }
                    else if (Directory.GetFiles(rootDir, filter).Length == 0)
                    {
                        // Check that the folder isn't empty
                        MessageBox.Show("No menu items in menu folder: " + rootDir + ". Exiting Menu app.", "CECompactStartMenu",
                            MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                        abort = true;
                    }
                }
            }

            if (!abort)
            {
                foreach (string dir in tempdirs)
                {
                    //A couple of folders to exclude if debugging
                    if (dir.ToLower() == "\\temp\\debugger")
                        continue;
                    else if (dir.ToLower() == "\\temp\\CECompactMyAppsMenu")
                        continue;
                    else if (dir.ToLower() == "\\temp\\CECompactStartMenu")
                        continue;


                    //Get .exes
                    string[] files = new String[]{};
                    if (filter != "*.lnk")
                        files= System.IO.Directory.GetFiles(dir, "*.exe");
                    //Failing that get shortcuts
                    if (files.Length==0)
                        files = System.IO.Directory.GetFiles(dir, "*.lnk");

                    if (files.Length == 0)
                        continue;

                    foreach (string fi in files)
                    {
                        System.IO.FileInfo fileInfo = new FileInfo(fi);
                        if (fileInfo.Exists)
                        {
                            fileList.Add(fileInfo);
                        }


                    }

                }
            }
            
            if (!abort)
            {          
                if (fileList.Count == 0)
                {
                    MessageBox.Show("No menu items in menu folder: " + rootDir + ". Exiting Menu app.", "CECompactStartMenu",
                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                    abort = true;;
                }
            }


            if (!abort)
            {
                var sortedApps =
                        from w in fileList
                        orderby w.Name
                        select w;

                fileList = sortedApps.ToList<FileInfo>();

                if (fileList.Count == 0) 
                {
                    MessageBox.Show("No menu items in menu folder: " + rootDir + ". Exiting Menu app.", "CECompactStartMenu",
                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                    abort = true;
                }
            }


            if (!abort) 
            {
                foreach (System.IO.FileInfo fi in fileList)
                {
                    string fn = fi.Name.Replace(".exe", "");
                    fn = fn.Replace(".lnk", "");
                    listBox1.Items.Add(fn);
                
                }

                int screenHeight = Screen.PrimaryScreen.WorkingArea.Height;
                this.Height = 30 + (listBox1.Items.Count * 165) / 10;
            
                if (! IsStartMenu )
                {
                    this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
                    this.Height += formTextAreaHeight;
                    if ((this.Height + formTextAreaHeight) > screenHeight)
                        this.Height = screenHeight - formTextAreaHeight;
                }
                else
                {
                    if ((this.Height ) > screenHeight)
                        this.Height = screenHeight ;
                }
            }

            if (abort)
                Application.Exit();

            

        }

        private void NotYetImplemented()
        {
            MessageBox.Show("Function not yet implemented", "CECompactStartMenu");
        }




        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex == -1)
                return;
            if (listBox1.SelectedIndex != 0)
            {
                FileInfo fi = fileList.ToArray<FileInfo>()[listBox1.SelectedIndex - 1];
                try
                {
                    DialogResult result = System.Windows.Forms.DialogResult.OK;
                    string args="";
                    if (!IsStartMenu)
                    {
                        result = Params.ShowAsDialog();
                        args = " " + Params.Args;
                    }
                    else
                    {
                    }
                    switch (result)
                    {
                        case System.Windows.Forms.DialogResult.OK:
                            

                            if (args != "start")
                            {
                                string filename = fi.FullName;
                                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                                proc.EnableRaisingEvents = false;
                                proc.StartInfo.FileName = filename;
                                proc.StartInfo.Arguments = args;
                                proc.Start();
                            }
                            else
                            {
                                //start filename
                                string filename = fi.FullName;
                                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                                proc.EnableRaisingEvents = false;
                                proc.StartInfo.FileName = args;
                                proc.StartInfo.Arguments = filename;
                                proc.Start();
                            }
                            break;
                        case  System.Windows.Forms.DialogResult.Cancel:
                            break;
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not run app. Original error: " + ex.Message);
                }
            }
            Application.Exit();

        }






    }
}
